package com.coalmine.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.coalmine.api.domain.ApiConfig;
import com.sun.research.ws.wadl.HTTPMethods;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: dbApi
 * @description:
 * @author: jiangqiang
 * @create: 2021-01-20 15:36
 **/
@Service
@Slf4j
public class ApiService {

    public Map<String, Object> getSqlParam(HttpServletRequest request, ApiConfig config) {
        //Map<String, String> parameter=getParameter(request);
        Map<String, Object> map = new HashMap<>();
        JSONArray requestParams = JSON.parseArray(config.getParams());
        for (int i = 0; i < requestParams.size(); i++) {
            JSONObject jo = requestParams.getJSONObject(i);
            String name = jo.getString("name");
            String type = jo.getString("type");

            //数组类型参数
            if (type.startsWith("Array")) {
                String[] values = request.getParameterValues(name);
                if (values != null) {
                    List<String> list = Arrays.asList(values);
                    if (values.length > 0) {
                        switch (type) {
                            case "Array<double>":
                                List<Double> collect = list.stream().map(value -> Double.valueOf(value)).collect(Collectors.toList());
                                map.put(name, collect);
                                break;
                            case "Array<bigint>":
                                List<Long> longs = list.stream().map(value -> Long.valueOf(value)).collect(Collectors.toList());
                                map.put(name, longs);
                                break;
                            case "Array<string>":
                            case "Array<date>":
                                map.put(name, list);
                                break;
                        }
                    } else {
                        map.put(name, list);
                    }
                } else {
                    map.put(name, null);
                }
            } else {
                String value= null;
                String method= request.getMethod();
                if (method.equals(HTTPMethods.GET.value())) {
                    String requestURLParam = request.getQueryString();
                    Map<String, String> paramMap = null;
                    if (StringUtils.isNotBlank(requestURLParam)) {
                        paramMap = getMap(requestURLParam);
                    } else {
                        paramMap = getParameter(request);
                    }
                    String val = paramMap.get(name);
                    if (StringUtils.isNotBlank(val)) {
                        try {
                            //处理% +特殊字符
                            val = val.replaceAll("%(?![0-9a-fA-F]{2})", "%25")
                                    .replaceAll("\\+", "%2B");
                            value = URLDecoder.decode(val, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                    //value = SqlUtil.replacer(val);
                }else {
                    value= request.getParameter(name);
                }
                if (StringUtils.isNotBlank(value)) {
                    switch (type) {
                        case "double":
                            Double v = Double.valueOf(value);
                            map.put(name, v);
                            break;
                        case "bigint":
                            Long longV = Long.valueOf(value);
                            map.put(name, longV);
                            break;
                        case "string":
                        case "date":
                            map.put(name, value);
                            break;
                    }
                } else {
                    map.put(name, value);
                }
            }
        }
        return map;
    }


    private Map<String, String> getParameter(HttpServletRequest request){
        // 由于不确定是否有参数 从request域中获取参数
        StringBuffer data = new StringBuffer();
        String line = null;
        BufferedReader reader = null;
        try {
            reader = request.getReader();
            while (null != (line = reader.readLine())) {
                data.append(line);
            }
        } catch (IOException e) {
            log.error("获取请求参数失败！");
            //return "获取请求参数失败！";
        }
        // 获取到的参数
        Map<String, String> params = getMap(data.toString());
        //String jsonString = data.toString();
        return params;
    }

    public static Map<String, String> getMap(String param) {
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isNotBlank(param)) {
            String[] arr = param.split("&");
            for (String s : arr) {
                String[] paramsArr = s.split("=");
                String key = paramsArr[0];
                if (paramsArr.length > 1) {
                    String value = paramsArr[1];
                    map.put(key, value);
                } else {
                    String value = null;
                    map.put(key, value);
                }
            }
        }
        return map;
    }

}
